import axios from 'axios'
import { ElMessage } from 'element-plus'

const headers = {}

const requestConfig = {
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 60000,
  headers
}

const service = axios.create(requestConfig)

const ERROR_MAP = {
  ERR_NETWORK: '网络错误！',
  400: '请求参数错误！',
  401: '请重新登录！',
  403: '暂无权限，请联系管理员！',
  404: '找不到资源！',
  405: '非法请求，禁止访问！',
  500: '服务器错误！',
  502: '网关错误，请稍后再试！',
  504: '网关错误！'
}

service.interceptors.request.use(
  (config) => {
    return config
  },
  (error) => {
    ElMessage.error('客户端异常')
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {
    if (response.data instanceof Blob) {
      return Promise.resolve(response.data)
    }
    // 本地环境，且接口指定调用mock数据
    if (import.meta.env.VITE_APP_MOCK === '1' && !!response.config['isMock']) {
      return Promise.resolve(response.data)
    }
    return Promise.resolve(response.data.data)
  },
  (error) => {
    if (!error.response) {
      const msg = ERROR_MAP[error.code]
      ElMessage.error(msg)
      return Promise.reject(error)
    }
    const msg = ERROR_MAP[error.response.status]
    if (msg) {
      ElMessage.error(msg)
    } else {
      ElMessage.error('服务器错误！')
    }
    return Promise.reject(error)
  }
)

export default service
